/**
 *  @desc 下拉框
 */
import React from 'react';
import { Select } from 'antd';
import Input from '../input';
import { getTempData } from "../_common/wrapXhr";
const { Option } = Select;
interface receiveProps {
  api?: Object;//接口参数，包含（url:接口地址，params:发送的数据，一旦发送数据默认GET）
  data?: Array<any>;//显示的数据，格式 ：['选项一', '选项二'] 或 [{ name: '选项一', code: 1 }, { name: '选项二', code: 2 }];
  map?: {
    value: 'code' | string | number,
    text: 'name' | string,
  } // 属性映射,未了匹配不同的业务
  extCode?: Array<string>; // 排除选中值
  placeholder?: string;
  editable?: Boolean;
  wrapResultData?: (a: any) => {};
  componentType?: 'Select' | 'Input';
  [key: string]: any;
}

export default class BiZSelect extends React.Component<receiveProps, any> {
  constructor(props: receiveProps) {
    super(props);
    let value: any = this.props.value;
    if (this.props.mode) {
      value = this.props.value ? this.props.value : [];
    }
    this.state = {
      data: [],
      value,
    }
  }

  componentWillReceiveProps(nextProps: any) {
    if (nextProps.api && JSON.stringify(nextProps.api) != JSON.stringify(this.props.api)) {
      this.getData(nextProps.api)
    }
    if (nextProps.value && JSON.stringify(nextProps.value) != JSON.stringify(this.state.value)) {
      if (this.props.sign == 1) {
        const value = this.props && this.props?.map?.value || 'code';
        this.setState({ value: nextProps.value[value] });
      } else {
        this.setState({ value: nextProps.value });
      }
    }
    /**
     * 表单重置为空时，重置只能Select组件state
     * @BUG #XRMDM-280 2019年10月10日15:41:03 周旺生
     */
    const nextValue = nextProps.value;
    if (!nextValue && (nextValue !== this.state.value)) {
      this.setState({ value: nextValue });
    }
  }

  componentDidMount() {
    if (this.props.api) {
      this.getData(this.props.api);
    }
  }

  getData = async (api: any) => {
    try {
      if (api?.url) {
        const data: any = await getTempData(api)
        const { extCode, wrapResultData } = this.props;
        // fix:设置一个包裹函数用来处理返回值不符合要求自定义
        let tempData = wrapResultData ? wrapResultData(data) : data;
        if (extCode && Array.isArray(extCode) && extCode.length) {
          tempData = data?.filter((item: any) => {
            return extCode.indexOf(item.code) < 0;
          });
        }
        this.setState({ data: tempData })
      }
    } catch (err) {
      console.warn(`select组件-getData发生错误:${err}`)
    }
  }

  onChange(value: any) {
    const { onChange } = this.props
    let { data = [], api } = this.props
    if (api)
      data = this.state.data
    if (onChange) {
      const v = this.props && this.props?.map?.value || 'code';
      const item = data.find(i => i[v] == value)
      if (this.props.sign == 1) {
        onChange(item, data, item)
      } else {
        onChange(value, data, item)
      }
    }
    this.setState({ value })
  }


  render() {
    const code = this.props && this.props?.map?.value || 'code';
    const name = this.props && this.props?.map?.text || 'name';
    let { data = [], api, objCode = 'code', mode, componentType } = this.props;
    let { value } = this.state;
    if (objCode && value && typeof value === 'object' && value[objCode]) {
      value = value[objCode];
    }
    if (mode === 'multiple' && !value) {
      value = [];
    }
    if (api)
      data = this.state.data


    return this.props.editable ? (componentType === 'Input' ? <Input {...this.props} /> : <Select {...this.props} onChange={this.onChange.bind(this)} value={value}>
      {
        data.length && data?.map((i: any, index: number) => {
          return <Option
            title={typeof (i) == 'object' ? i[name] : i}
            value={typeof (i) == 'object' ? i[code] : i}
            key={index}>{typeof (i) == 'object' ? i[name] : i}</Option>
        }) || <></>
      }
    </Select>) : <span>{this.props.value}</span>
  }
}
